package system

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/hashicorp/go-uuid"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/tools"
	"go-admin/tools/alipay"
	"go-admin/tools/app"
	"strconv"
	"strings"
	"time"
)

/**
* @Description:
* @Author: yuweizhu
* @Date: 2020/11/5 1:39 上午
**/

func QueryOrderDetail(c *gin.Context) {
	var data models.TOrder
	var id int
	var err error

	if value := c.Param("id"); value != "" {
		id, err = tools.StringToInt(value)
	}
	data.ID= uint(id)
	result, err := data.GetById()
	tools.HasError(err, "", -1)
	app.OK(c, result, "")
}

func QueryRightsConfig(c *gin.Context)  {
	var data models.TRightsConfig
	app.OK(c, data.GetAll(), "")
}

func ModifyOrder(c *gin.Context) {
	var data models.SysUser
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	id, err := data.Update(orm.GetDb(), data.UserId)
	tools.HasError(err, "修改失败", 500)
	app.OK(c, id, "修改成功")
}

// 流量包订单
func CreateOrder(c *gin.Context) {
	tx := orm.GetDb().Begin()
	var data models.TOrder
	var rights models.TRights
	var rightsConfig models.TRightsConfig
	var account models.TAccount
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)
	account.UserId = data.UserId
	account.Amount = data.Amount
	if account.ValidateAmount() != 1 {
		tools.HasError(errors.New("余额不足，请先充值"), "余额不足，请先充值", 500)
		return
	}

	rightsConfig.ID = data.RightsId
	config, err := rightsConfig.Get()
	if err != nil || config == nil {
		tools.HasError(err, "添加失败", 500)
		return
	}
	data.PayType = 1
	data.Type = 2
	data.Amount = config.Costs
	data.OrderNo = generateOrderNo()
	data.Product = config.Product
	data.Status = 2
	err = data.Insert(tx)
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "添加失败", 500)
		return
	}

	rights.RightsId = config.ID
	rights.Value = config.Value
	rights.RemainValue = config.Value
	rights.UserId = data.UserId
	rights.StartTime = time.Now()
	rights.EndTime = rights.StartTime.AddDate(0, 0, 120)
	rights.CreatedAt = time.Now()
	rights.UpdatedAt = time.Now()
	err = rights.Insert(tx)
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "添加失败", 500)
		return
	}
	err = account.DecreaseAmount(tx)
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "添加失败", 500)
		return
	}
	tx.Commit()
	app.OK(c, data.OrderNo, "购买成功")
}

// 余额订单
func CreateRechargeOrder(c *gin.Context) {
	tx := orm.GetDb().Begin()
	var data models.TOrder
	//var account models.TAccount
	//var user models.SysUser
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	data.OrderNo = generateOrderNo()
	data.Amount = data.RechargeAmount
	data.Product = "充值" + strconv.Itoa(data.RechargeAmount) + "元"
	data.Status = 1
	data.Type = 1
	data.PayType = 1
	err = data.InsertRechargeOrder(tx)
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "添加失败", 500)
		return
	}

	//// TODO 回调增加余额
	//account.UserId = data.UserId
	//account.Amount = data.Amount
	//err = account.IncreaseAmount(tx)
	//if err != nil {
	//	tx.Rollback()
	//	tools.HasError(err, "添加失败", 500)
	//	return
	//}
	//account = models.TAccount{}
	//account.UserId = data.UserId
	//resultAccount, err := account.Get()
	//tools.HasError(err, "用户不存在", 500)
	//
	//if resultAccount.SumAmount == 0 {
	//	user.StarLevel = 0
	//} else if resultAccount.SumAmount < 500 {
	//	user.StarLevel = 0
	//} else if resultAccount.SumAmount < 1000 {
	//	user.StarLevel = 1
	//} else if resultAccount.SumAmount < 2000 {
	//	user.StarLevel = 2
	//} else {
	//	user.StarLevel = 3
	//}
	//user.UserId = int(data.UserId)
	//_, _ = user.Update(user.UserId)
	tx.Commit()
	data.Url = alipay.CreateAlipayOrder(data.OrderNo, data.Amount, data.Product)
	app.OK(c, models.TOrder{ID: data.ID, OrderNo: data.OrderNo, Url: data.Url}, "添加成功")

}

func generateOrderNo() string {
	str, _ := uuid.GenerateUUID()
	return "DDO" + strings.ToUpper(strings.Replace(str, "-", "", -1))
}

func GetOrderList(c *gin.Context) {
	var data models.TOrder
	var err error
	var pageSize = 10
	var pageIndex = 1
	var pageUserId = 0

	size := c.Request.FormValue("pageSize")
	if size != "" {
		pageSize, err = tools.StringToInt(size)
	}

	index := c.Request.FormValue("pageIndex")
	if index != "" {
		pageIndex, err = tools.StringToInt(index)
	}

	userId := c.Request.FormValue("userId")
	if userId != "" {
		pageUserId , err = tools.StringToInt(userId)
	}

	pageType := c.Request.FormValue("type")
	if pageType != "" {
		data.Type , err = tools.StringToInt(index)
	}

	data.UserId = int64(pageUserId)
	result, count, err := data.GetPage(pageSize, pageIndex)
	for idx, val := range result {
		if val.Status == 1 {
			result[idx].StatusResult = "支付中"
		}
		if val.Status == 2 {
			result[idx].StatusResult = "支付成功"
		}
	}
	tools.HasError(err, "", -1)

	app.PageOK(c, result, int(count), pageIndex, pageSize, "")
}

